package com.ygu.HomeWork.NO01;


import java.util.Objects;

public class PrintLeaner {
    public static void main(String[] args) {
        Student[] students = {new Student("aa","java"),new Student("ab","java"),new Student("ba","cpp"),new Student("bb","cpp"),new Student("ca","python"),new Student("cb","python")};
        Student student = initLinkedList(students);
        System.out.println(toString(student));
        System.out.println("========================================");
        Student newStudent = new Student("ac","java");
        Student addStudent = addStudent(student, newStudent);
        System.out.println(toString(addStudent));
    }

    public static Student addStudent(Student studentHead,Student newStudent){
        return getLastJavaStudent(studentHead,newStudent);
    }

    public static Student getLastJavaStudent(Student studentHead, Student newStudent) {
        if (studentHead == null) {
            return newStudent;  // 如果链表为空，则直接返回新节点作为头节点
        }

        Student current = studentHead;
        while (current.next != null) {
            if (Objects.equals(current.language, newStudent.language)) {
                // 找到相应语言的节点，将新节点添加到该语言节点的尾部
                while (current.next != null && Objects.equals(current.next.language, newStudent.language)) {
                    current = current.next;
                }
                newStudent.next = current.next;
                current.next = newStudent;
                return studentHead;
            }
            current = current.next;
        }

        // 如果没有找到相应语言的节点，则将新节点添加到链表末尾
        current.next = newStudent;
        return studentHead;  // 返回原始链表的头节点
    }

    /**
     * 初始化链表
     */
    private static Student initLinkedList(Student[] array) {
        Student head = null, cur = null;
        for (int i = 0; i < array.length; i++) {
            Student newNode = new Student(array[i]);
            newNode.next = null;
            if (i == 0) {
                head = newNode;
                cur = head;
            } else {
                cur.next = newNode;
                cur = newNode;
            }
        }
        return head;
    }

    public static String toString(Student head) {
        Student current = head;
        StringBuilder sb = new StringBuilder();
        while (current != null) {
            sb.append(current.name).append("\t");
            current = current.next;
        }
        return sb.toString();
    }
}
